from wx import wx
#import sqlite3
#import AddInteractionDialog

# Create Content Class
class CreateInteractionTab(wx.Panel):
    
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        self.toolbar_ADDIACTION = wx.NewId()
        self.toolbar_DELIACTION = wx.NewId()
        self.toolbar_UPDATEIACTION = wx.NewId()
        self.iactionToolbar = self.MakeInteractionToolBar()
        self.iactionViewer = wx.Panel(self, style=wx.BORDER_SUNKEN)
        self.iactionViewer.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW))
        self.interactionListBox = wx.ListBox(self, -1,size=wx.Size(100, -1), style= wx.BORDER_SUNKEN | wx.LB_SINGLE | wx.LB_NEEDED_SB)
        self.mainBox = wx.BoxSizer(wx.VERTICAL)
        self.botBox = wx.BoxSizer(wx.HORIZONTAL)
        self.topBox = wx.BoxSizer(wx.HORIZONTAL)
        self.topBox.Add(self.iactionToolbar, 1, wx.ALL | wx.ALIGN_LEFT | wx.EXPAND)
        self.botBox.Add(self.interactionListBox, 0, wx.ALL | wx.ALIGN_LEFT | wx.EXPAND)
        self.botBox.Add(self.iactionViewer, 1, wx.EXPAND)
        self.mainBox.Add(self.topBox, 0, wx.ALL | wx.ALIGN_LEFT | wx.EXPAND)
        self.mainBox.Add(self.botBox, 1, wx.EXPAND)
        self.SetSizer(self.mainBox)

        wx.EVT_LISTBOX(self, self.interactionListBox.GetId(), self.OnSelectedInteractionItem)
        
        sizer = wx.BoxSizer(wx.VERTICAL)
        box = wx.BoxSizer(wx.HORIZONTAL)
        label = wx.StaticText(self.iactionViewer, -1, "Type:")
        label.SetHelpText("Select The type of interaction to build.")
        box.Add(label, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
        self.typeChoice = wx.Choice(self.iactionViewer, -1, (100, 50), choices = ['Multiple Choice', 'Multiple Select'])
        self.typeChoice.SetHelpText("Select Interaction Type")
        box.Add(self.typeChoice, 1, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
        self.afeedCheck = wx.CheckBox(self.iactionViewer, -1, "Include Answer Feedback", style=wx.ALIGN_RIGHT)
        self.afeedCheck.SetHelpText("Include custom feedback for each answer")
        box.Add(self.afeedCheck, 1, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
        sizer.Add(box, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
        
        box2 = wx.BoxSizer(wx.HORIZONTAL)
        label = wx.StaticText(self.iactionViewer, -1, "# of Attempts:")
        label.SetHelpText("Set the Number of Attempts")
        box2.Add(label, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
        self.attemptSpinner = wx.SpinCtrl(self.iactionViewer, -1, "1", (5, 50))
        self.attemptSpinner.SetRange(1, 10)
        self.attemptSpinner.SetHelpText("Set the Number of Attempts")
        box2.Add(self.attemptSpinner, 1, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
        label = wx.StaticText(self.iactionViewer, -1, "Weight:")
        box2.Add(label, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
        self.weightSpinner = wx.SpinCtrl(self.iactionViewer, -1, "1", (5, 50))
        self.weightSpinner.SetRange(1, 10)
        self.weightSpinner.SetHelpText("How many questions the question is worth")
        box2.Add(self.weightSpinner, 1, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 2)
        self.gradedCheck = wx.CheckBox(self.iactionViewer, -1, "Graded", style=wx.ALIGN_RIGHT)
        self.gradedCheck.SetHelpText("Will the Question be graded and use the weight value")
        box2.Add(self.gradedCheck, 1, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 2)
        sizer.Add(box2, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
        
        box3 = wx.BoxSizer(wx.HORIZONTAL)
        label = wx.StaticText(self.iactionViewer, -1, "Question Text:")
        box3.Add(label, 0, wx.ALIGN_LEFT|wx.ALIGN_TOP, 5)
        self.questionText = wx.TextCtrl(self.iactionViewer, -1, "", size=(-1, 100), style=wx.TE_MULTILINE)
        self.questionText.SetHelpText("Add Question Text Here")
        box3.Add(self.questionText, 1, wx.ALIGN_LEFT|wx.GROW|wx.EXPAND, 5)
        sizer.Add(box3, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
        
        box4 = wx.BoxSizer(wx.HORIZONTAL)
        label = wx.StaticText(self.iactionViewer, -1, "Correct Feedback:")
        box4.Add(label, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
        self.correctText = wx.TextCtrl(self.iactionViewer, -1, "")
        self.correctText.SetHelpText("Provide Feedback for Correct Answer")
        box4.Add(self.correctText, 1, wx.ALIGN_LEFT|wx.ALL, 5)
        sizer.Add(box4, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL, 5)

        box4 = wx.BoxSizer(wx.HORIZONTAL)
        label = wx.StaticText(self.iactionViewer, -1, "Incorrect Feedback:")
        box4.Add(label, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
        self.incorrectText = wx.TextCtrl(self.iactionViewer, -1, "")
        self.incorrectText.SetHelpText("Provide Feedback for Incorrect Answer")
        box4.Add(self.incorrectText, 1, wx.ALIGN_LEFT|wx.GROW|wx.ALL, 5)
        sizer.Add(box4, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
        '''
        self.Bind(wx.EVT_CHOICE, self.EvtChoice, self.ch)


        def EvtChoice(self, event):
            self.log.WriteText('EvtChoice: %s\n' % event.GetString())
            self.ch.Append("A new item")
        '''
        self.iactionViewer.SetSizer(sizer)
        sizer.Fit(self.iactionViewer)
        self.iactionViewer.Show(False)

        
    # Create Event Function
    def OnSelectedInteractionItem(self, event):
        if(self.interactionListBox.GetSelection() != -1):
            self.TopLevelParent.DisplayDebug("on selection change")
            '''
            tmpString = self.interactionListBox.GetStringSelection()
            tmpString2 = tmpString.split(".", 1)
            self.content = self.TopLevelParent.currentContentDict[int(tmpString2[0])]
            self.content = self.content[0].encode("UTF-8")
            out = StringIO()
            handler = wx.richtext.RichTextXMLHandler()
            txtBuffer = self.createContentRichTextCtrl.GetBuffer()
            txtBuffer.AddHandler(handler)
            out.write(self.content)
            out.seek(0)
            handler.LoadStream(txtBuffer, out)
            out.close()
            self.createContentRichTextCtrl.Refresh()
            '''

    # Create RichText Toolbar
    def MakeInteractionToolBar(self):
        tb = wx.ToolBar(self, -1, style=wx.TB_FLAT | wx.NO_BORDER)
        self.ToolBar = tb
        tb.AddTool(self.toolbar_ADDIACTION, wx.Bitmap("images/list-add.png", wx.BITMAP_TYPE_PNG), isToggle=False, shortHelpString="Add New Interaction")
        tb.AddTool(self.toolbar_DELIACTION, wx.Bitmap("images/list-remove.png", wx.BITMAP_TYPE_PNG), isToggle=False, shortHelpString="Delete Selected Interaction")
        tb.AddSeparator()
        tb.AddTool(self.toolbar_UPDATEIACTION, wx.Bitmap("images/document-save.png", wx.BITMAP_TYPE_PNG), isToggle=False, shortHelpString="Update Existing Content")
        
        tb.EnableTool(self.toolbar_DELIACTION, False)
        tb.EnableTool(self.toolbar_UPDATEIACTION, False)
        
        wx.EVT_TOOL(self, self.toolbar_ADDIACTION, self.AddInteraction)
        wx.EVT_TOOL(self, self.toolbar_DELIACTION, self.DelInteraction)
        wx.EVT_TOOL(self, self.toolbar_UPDATEIACTION, self.UpdateInteraction)
        
        tb.Realize()
        
        return tb

    # Create Event Function
    def AddInteraction(self, event):
        self.TopLevelParent.DisplayDebug("add interaction")
        self.iactionToolbar.EnableTool(self.toolbar_UPDATEIACTION, True)
        self.iactionToolbar.EnableTool(self.toolbar_DELIACTION, True)
        
        self.iactionViewer.Show(True)
        self.Layout()
        '''
        self.addInteractionDialog = AddInteractionDialog.AddInteractionDialog(self, -1, "Add Interaction to Course", size=(350, 200), style=wx.DEFAULT_DIALOG_STYLE)
        self.addInteractionDialog.CenterOnParent()
        
        if(self.addInteractionDialog.ShowModal() == wx.ID_OK):
            self.TopLevelParent.DisplayDebug("add initial information")
        
        self.addInteractionDialog.Destroy()
        '''
        # should be disabled until someone enters content...
        '''
        self.addImageDialog = AddImageDialog.AddImageDialog(self, -1, "Add Image to Course", size=(350, 200), style=wx.DEFAULT_DIALOG_STYLE)
        self.addImageDialog.CenterOnParent()
        
        if(self.addImageDialog.ShowModal() == wx.ID_OK):
            self.data = open(self.TopLevelParent.opj(self.addImageDialog.imageFileText.GetValue()), "rb").read()
            self.layoutValue =  self.addImageDialog.imageAltText.GetValue() + "::" + self.addImageDialog.imageTitleText.GetValue()
            con = sqlite3.connect(self.TopLevelParent.database)
            cur = con.cursor()
            cur.execute("INSERT INTO ResourceTable(resourceTypeID, layout, resourceData, courseID) VALUES(2, ?, ?, ?)", (self.layoutValue, base64.encodestring(sqlite3.Binary(self.data)), self.TopLevelParent.currentCourseID))
            con.commit()
            con.close()
            # write the data to db...
            self.TopLevelParent.currentImageDict = self.TopLevelParent.RefreshListBox(self.imageListBox, self.TopLevelParent.currentCourseID, 2, None)
            self.TopLevelParent.DisplayDebug("You pressed OK")
            
        else:
            self.TopLevelParent.DisplayDebug("You pressed Cancel")
            
        self.addImageDialog.Destroy()
        out = StringIO()
        handler = wx.richtext.RichTextXMLHandler()
        txtBuffer = self.createContentRichTextCtrl.GetBuffer()
        handler.SaveStream(txtBuffer, out)
        out.seek(0)
        self.content = out.read()
        out.close()
        con = sqlite3.connect(self.TopLevelParent.database)
        cur = con.cursor()
        cur.execute("INSERT INTO ResourceTable(resourceData, courseID, resourceTypeID) VALUES(?, ?, 1)", (self.content, self.TopLevelParent.currentCourseID))
        con.commit()
        con.close()
        self.TopLevelParent.currentContentDict = self.TopLevelParent.RefreshListBox(self.interactionListBox, self.TopLevelParent.currentCourseID, 1, None)
        # put code in here to refresh available resources list box...
        # or we could just put code to refresh available resources list box when you select the layout tab button...
        # if that loads too quickly, then do it here
        '''
    
    def DelInteraction(self, event):
        self.TopLevelParent.DisplayDebug("del selected interaction")
        
    def UpdateInteraction(self, event):
        self.TopLevelParent.DisplayDebug("save interaction")
        '''
        tmpString = self.interactionListBox.GetStringSelection()
        tmpString2 = tmpString.split(".", 1)
        out = StringIO()
        handler = wx.richtext.RichTextXMLHandler()
        txtBuffer = self.createContentRichTextCtrl.GetBuffer()
        handler.SaveStream(txtBuffer, out)
        out.seek(0)
        self.content = out.read()
        out.close()
        con = sqlite3.connect(self.TopLevelParent.database)
        cur = con.cursor()
        cur.execute("UPDATE ResourceTable set resourceData = (?) where resourceID = (?)", (self.content, int(tmpString2[0]),))
        con.commit()
        con.close()
        self.TopLevelParent.currentContentDict = self.TopLevelParent.RefreshListBox(self.interactionListBox, self.TopLevelParent.currentCourseID, 1, None)
        # put code in here to refresh available resources list box...
        # or we could just put code to refresh available resources list box when you select the layout tab button...
        # if that loads too quickly, then do it here
        '''
'''
# Is Question Tracked for Score or Review.
# Type of Question: multiple choice, multiple select, fill in the blank, category matching
# Number of attempts to get question right
# weight for scoring purposes
# if review, then auto answer question
# if wrong, move on so u could fail, send back to learn more and retry, try again with less points
# Decreasing Credit = value of question per attempt
# ref page is page to go back to
# jump page is page to return to question.
# question text
# answer correct = true
# answer
# right feedback
# wrong feedback
# answer feedback specific to each answer
<question track="false" type="Multiple Choice" attempts="2" weight="1" onReview="false" onWrong="moveOn" decreasingCredit="" refPage="1">
    <questionText><![CDATA[The Office for Victim Assistance was established in 2001 as a result of:]]></questionText>
    <answer correct="true"><![CDATA[Attorney General Guidelines ]]></answer>
    <answer><![CDATA[Taxpayer request]]>
    </answer>

    <answer><![CDATA[Congressional mandate ]]>
    </answer>
    <feedback>
        <right><![CDATA[ Correct.  The Office of Victim Assistance was established in 2001 as a result of the Attorney General Guidelines on Victim and Witness Assistance.]]></right>
        <wrong><![CDATA[ Incorrect. The Office of Victim Assistance was established in 2001 as a result of the Attorney General Guidelines on Victim and Witness Assistance.]]></wrong>
    </feedback>
</question>
<question track="false" type="Fill in the Blank" attempts="2" weight="2" onReview="true" onWrong="moveOn" decreasingCredit="">
    <questionText><![CDATA[Testing |one| two three is a |BareNaked Ladies| song.]]></questionText>
    <feedback>
        <right>Correct.</right>
        <wrong>Incorrect</wrong>
    </feedback>
</question>
<question track="false" type="Category Matching" attempts="2" weight="2" onReview="true" onWrong="moveOn" decreasingCredit="">
    <questionText><![CDATA[Giraffe |animal|<br>Banana |fruit|<br>Quartz |mineral|<br/>Orange |fruit|]]></questionText>
    <answer><![CDATA[vegetable]]></answer>
    <feedback>
        <right>Correct.</right>
        <wrong>Incorrect</wrong>
    </feedback>
</question>
<question track="false" type="Multiple Select" attempts="3" weight="2" onReview="true" onWrong="decreaseValue" decreasingCredit="1,0.5" refPage="1" jumpPage="1">
    <questionText><![CDATA[ How are you today? ]]></questionText>
    <answer correct="true"><![CDATA[ Great ]]></answer>
    <answer correct="true"><![CDATA[ Okay ]]></answer>
    <answer><![CDATA[ Sleepy ]]></answer>
    <answer><![CDATA[ Sinusey ]]></answer>
    <feedback>
        <right><![CDATA[ Correct. Reasoning ]]></right>
        <wrong><![CDATA[ Incorrect. Reasoning ]]></wrong>
    </feedback>
</question>
<question track="true" type="Multiple Choice" attempts="2" weight="1" onReview="false" onWrong="backLO" decreasingCredit="" refPage="4" jumpPage="5">
    <questionText><![CDATA[ How are you today? ]]></questionText>
    <answer correct="true"><![CDATA[ Great ]]></answer>
    <answer><![CDATA[ Okay ]]>
        <answerFeedback><![CDATA[Okay is wrong.]]></answerFeedback>
    </answer>
    <answer><![CDATA[ Sleepy ]]>
        <answerFeedback><![CDATA[Sleepy is wrong.]]></answerFeedback>
    </answer>
    <answer><![CDATA[ Sinusey ]]></answer>
    <feedback>
        <right><![CDATA[ Correct. Reasoning ]]></right>
        <wrong><![CDATA[ Incorrect. Reasoning ]]></wrong>
    </feedback>
</question>
'''